package com.yulang.security.strategy;

import com.yulang.security.handler.CustomAuthFailureHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.session.SessionInformationExpiredEvent;
import org.springframework.security.web.session.SessionInformationExpiredStrategy;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import java.io.IOException;

@Component
public class CustomSessionExpiredStrategy implements SessionInformationExpiredStrategy {


    @Autowired
    private CustomAuthFailureHandler customAuthFailureHandler;

    @Override
    public void onExpiredSessionDetected(SessionInformationExpiredEvent event) throws IOException {
        UserDetails principal = (UserDetails)event.getSessionInformation().getPrincipal();

        AuthenticationServiceException authenticationServiceException = new AuthenticationServiceException("用户已在另一台电脑登录");
        try {
            event.getRequest().setAttribute("toLogin",true);
            customAuthFailureHandler.onAuthenticationFailure(event.getRequest(),event.getResponse(),authenticationServiceException);
        } catch (ServletException e) {
            e.printStackTrace();
        }
    }
}
